package com.heima.wemedia.interceptor;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.entity.WmMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WmTokenInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头获取到id
        String userId = request.getHeader("userId");
        //判断id是否为空
        if (StringUtils.isNotBlank(userId)) {
            //不为空将id存入Thread中
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(Long.parseLong(userId));
            WmThreadLocalUtil.setId(wmMaterial);
            //放行
            return super.preHandle(request, response, handler);
        }
        //否则返回数据给浏览器 表示id不存在
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(responseResult));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清理线程数据
        WmThreadLocalUtil.remove();
        super.postHandle(request, response, handler, modelAndView);
    }
}
